//
//  YQUserCenterHeaderViewModel.m
//  industry
//
//  Created by 王雅强 on 2021/1/26.
//  Copyright © 2021 Haier. All rights reserved.
//

#import "YQUserCenterHeaderViewModel.h"
#import "YQImagePickerManager.h"
#import "XLUploadFileTool.h"
#import "XLUserDefaults.h"
#import "NSData+Image.h"

@implementation YQUserCenterHeaderViewModel



-(void)setAvatarImage{
    
    
    UIAlertController * alerVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * ac1 = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                weakSelf.currentTopController
        
         [[YQImagePickerManager sharedInstance] photoTypeCropWithTopVc:self.currentTopController photo:^(UIImage * _Nonnull cropImage) {
             XLLog(@"从相册中选取结束");
                 [self uploadImage:cropImage];
        }];
       
        
    }];
    UIAlertAction * ac2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [[YQImagePickerManager sharedInstance] cameraTypeCropWithTopVc:self.currentTopController photo:^(UIImage * _Nonnull cropImage) {
            XLLog(@"拍照");
            [self uploadImage:cropImage];
        }];
    }];
    UIAlertAction * ac3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alerVC addAction:ac1];
    [alerVC addAction:ac2];
    [alerVC addAction:ac3];
    
    
    [self.currentTopController.navigationController presentViewController:alerVC animated:YES completion:nil];
    
}


-(void)uploadImage:(UIImage *)image{
    if (!image) return;
    
    NSData *data = [NSData reSizeImageData:image maxImageSize:0 maxSizeWithKB:800];
    [self requestOSSSecurityTokenResponseCallbackBlock:^(NSDictionary * responseData) {
        if (responseData[@"result_code"]) {
            
            [self uploadAvaterDataToServer:data responseCallbackBlock:^(NSDictionary * responseData) {
                
                if (responseData[@"filePath"]) {
                    
                    [self updateHeadPortraitUrlStatuswith:responseData[@"filePath"] successBlock:^(NSDictionary *dict) {
                        self.avatarIm = image;
                        [XLToast showSuccessMessage:@"头像上传成功"];
                        XL_UserInfoData.avatar = responseData[@"filePath"];
                        [[XLUserData sharedXLUserData] saveCurrentUserInfo:XL_UserInfoData];
                    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
                        [XLToast showSuccessMessage:@"头像上传失败"];
                    }];
                }
                
                
            }];
            
        }
//
    }];
    
    
}




/**
 *用于获取securityToken并上传
 *
 * @param datas 用于数据数组
 *
 * @param operationType 1表示直接获取securityToken   2表示上传图片获取securityToken 3表示上传视频获取securityToken   4表示删除图片或视频获取，获取securityToken
 *
 */
- (void)requestOSSSecurityTokenResponseCallbackBlock:(void (^)(id responseData))responseCallbackBlock {
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (!ISEmptyString(XL_UserInfoData.securityToken)) {
        [params setValue:XL_UserInfoData.securityToken forKey:@"securityToken"];
    }
    
    [request requestWithMethod:XLHttpMedthTypeGET url:XLFetchOSSTokenUrl params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        
        id temData = [dict objectForKey:@"data"];
        if ([temData isKindOfClass:[NSDictionary class]]) {
            [[XLUploadFileTool sharedInstance] initClientWithServerDic:temData];
            responseCallbackBlock(@{@"result_code":@(YES)});
          
       
        } else {
            responseCallbackBlock(@{@"result_code":@(NO)});
        }

    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
         responseCallbackBlock(@{@"result_code":@(NO)});
    }];
}

//上传头像OSS
- (void)uploadAvaterDataToServer:(NSData *)data
      responseCallbackBlock:(void (^)(id responseData))responseCallbackBlock {
    [[XLUploadFileTool sharedInstance] uploadAvaterData:data successBlock:^(NSDictionary *dict) {
        responseCallbackBlock(dict);

        XLLog(@"上传头像OSS内容:>>>>>%@", dict);
        
    } failBlock:^(NSError *error, XLNetworkReachabilityStatus reachabilityStatus) {
        XLLog(@"上传头像OSS失败:>>>>>");
        responseCallbackBlock(@{@"result_code":@(NO)});
    }];
     

}

//上传头像url
- (void)updateHeadPortraitUrlStatuswith:(NSString *)url successBlock:(void(^)(NSDictionary *dict))successBlock failBlock:(void(^)(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict)) failBlock {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:url forKey:@"avatar"];
    
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    [request requestWithMethod:XLHttpMedthTypePOST url:XLUpdateHeadPortraitUrl params:params isExtraParams:NO successBlock:successBlock failBlock:failBlock];

}

- (void)getAvatarImageUrlWithPaht:(NSString *)filePath success:(void (^)(NSString * url))complete{
    [self requestOSSSecurityTokenResponseCallbackBlock:^(NSDictionary * responseData) {
        if (responseData[@"result_code"]) {
            complete([[XLUploadFileTool sharedInstance] presignConstrainwithObjectKey:filePath]);
        }
    }];
}



@end
